﻿using AutoMapper;
using DotNetCore.CAP;
using IMES.Common.Domain.KeepModel.Process;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using NPOI.SS.Formula.Functions;
using System.Diagnostics.Metrics;
using System.Transactions;

namespace Keep.API.Appliction.Command.ProcessFile
{
	/// <summary>
	/// // 新增流程、
	/// </summary>
	public class ProcessRouteCreateHandler : IRequestHandler<ProcessRouteCreateCommon, Result>
	{
		private readonly IBaseRepositorys<WorkingProcedure> _workingProcedureRepository;
		private readonly IBaseRepositorys<ProcessRoute> _processRouteRep;
		private readonly IMapper _mapper;
		//private readonly ICapPublisher _capPublisher;, ICapPublisher capPublisher_capPublisher = capPublisher;

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="processRouteRep"></param>
		/// <param name="mapper"></param>
		public ProcessRouteCreateHandler(IBaseRepositorys<WorkingProcedure> workingProcedureRepository, IBaseRepositorys<ProcessRoute> processRouteRep, IMapper mapper)
		{
			_workingProcedureRepository = workingProcedureRepository;
			_processRouteRep = processRouteRep;
			_mapper = mapper;
			
		}
		/// <summary>
		/// 处理新增流程
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public Task<Result> Handle(ProcessRouteCreateCommon request, CancellationToken cancellationToken)
		{
			var result = new Result { Code = (int)CodeEnum.success, Messege = "新增流程成功" };
			try
			{
				 
					var processRoute = _mapper.Map<ProcessRoute>(request.CreateProcessRoute);
					processRoute.ProcessRouteNumber = GetMaxProcessRouteNumber(); // 生成流程编号
					processRoute.CreateDate = DateTime.Now;
					var list = _processRouteRep.Add(processRoute);
					if (list == 0)
					{
						throw new Exception("新增流程失败"); // 将添加失败的情况通过抛异常统一处理
					}
					var lists = _processRouteRep.GetAll().FirstOrDefault(c => c.ProcessRouteNumber == processRoute.ProcessRouteNumber);
					//var allRoutes = _processRouteRep.GetAll().ToList(); // 将数据加载到内存中
					//var lists = allRoutes.Where(c => c.ProcessRouteNumber == processRoute.ProcessRouteNumber).First();
					foreach (var item in request.WorkingProcedure)
					{
						item.ProcessRouteId = lists.ProcessRouteId;
						item.CreateDate = DateTime.Now;
						
					}

					var list1 = _workingProcedureRepository.AddRange(request.WorkingProcedure);
					if (list1 == null)
					{
						throw new Exception("添加失败");
					}
					 
					return Task.FromResult(result);
				 
			

			}
			catch (Exception )
			{
				result.Code = (int)CodeEnum.error;
				result.Messege = "新增流程失败";
			}
			return Task.FromResult(result); // 直接返回结果，编译器会自动包装为Task<Result>
		}
		/// <summary>
		/// 获取最大流程编号
		/// </summary>
		/// <returns></returns>
		private string GetMaxProcessRouteNumber()
		{
			var list = _processRouteRep.GetAll().Max(a => a.ProcessRouteId);
			return GenerateId(list + 1);
		}
		/// <summary>
		/// 前缀
		/// </summary>
		private static readonly string prefix = "GYLX";
		/// <summary>
		/// 生成流程编号
		/// </summary>
		/// <param name="counter"></param>
		/// <returns></returns>
		public static string GenerateId(int counter)
		{
			string datetimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
			string sequenceStr = counter.ToString("D5");
			string result = prefix + datetimeStr + sequenceStr;
			return result;
		}

	}
}
